package com.example.hyperledger_fabric_by_java.com.test.fabric.controller;

import com.example.hyperledger_fabric_by_java.com.test.fabric.entity.Asset;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import org.apache.tomcat.util.codec.binary.StringUtils;
import org.hyperledger.fabric.client.Contract;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/asset")
@AllArgsConstructor
public class AssetContractController {

    final Contract contract;

    @GetMapping("test")
    public String test() {
        return "test";
    }

    @PutMapping("/")
    public Map<String, Object> createCat(@RequestBody Asset asset) throws Exception {

        Map<String, Object> result = Maps.newConcurrentMap();

        byte[] bytes = contract.submitTransaction("CreateAsset",
                asset.getAssetId(), asset.getColor(), String.valueOf(asset.getSize()),
                asset.getOwner(), String.valueOf(asset.getAppraisedValue()));

        result.put("payload", StringUtils.newStringUtf8(bytes));
        result.put("status", "ok");
        return result;
    }

    @PutMapping("/async")
    public Map<String, Object> createAssetAsync(@RequestBody Asset asset) throws Exception {
        Map<String, Object> result = Maps.newConcurrentMap();
        contract.newProposal("CreateAsset")
                .addArguments(asset.getAssetId(), asset.getColor(), String.valueOf(asset.getSize()),
                        asset.getOwner(), String.valueOf(asset.getAppraisedValue()))
                .build()
                .endorse()
                .submitAsync();
        result.put("status", "ok");

        return result;
    }
}
